<template>
  <div id="app">
    <!-- 侧边栏 -->
    <div class="sidebar" :class="{ 'sidebar-collapsed': isSidebarCollapsed }">
      <div class="sidebar-header">
        <button class="toggle-sidebar" @click="toggleSidebar">
          {{ isSidebarCollapsed ? '→' : '←' }}
        </button>
        <h3 v-if="!isSidebarCollapsed">功能菜单</h3>
      </div>
      
      <div class="sidebar-content">
        <!-- 查询按钮 -->
        <button class="sidebar-btn" :class="{ active: activeTab === 'query' }" @click="setActiveTab('query')">
          <span class="btn-icon">🔍</span>
          <span v-if="!isSidebarCollapsed">查询</span>
        </button>
        
        <!-- AI问答按钮 -->
        <button class="sidebar-btn" :class="{ active: activeTab === 'ai' }" @click="setActiveTab('ai')">
          <span class="btn-icon">🤖</span>
          <span v-if="!isSidebarCollapsed">AI问答</span>
        </button>
        
        <!-- 保存/加载按钮 -->
        <button class="sidebar-btn" :class="{ active: activeTab === 'save' }" @click="setActiveTab('save')">
          <span class="btn-icon">💾</span>
          <span v-if="!isSidebarCollapsed">保存/加载</span>
        </button>
        
        <!-- 账户信息按钮 -->
        <button class="sidebar-btn account-btn" :class="{ active: activeTab === 'account' }" @click="setActiveTab('account')">
          <span class="btn-icon">👤</span>
          <span v-if="!isSidebarCollapsed">账户信息</span>
        </button>

        <!-- 设置按钮 -->
        <button class="sidebar-btn settings-btn" :class="{ active: activeTab === 'settings' }" @click="setActiveTab('settings')">
          <span class="btn-icon">⚙️</span>
          <span v-if="!isSidebarCollapsed">设置</span>
        </button>
      </div>
    </div>

    <div class="main-content" :class="{ 'sidebar-expanded': !isSidebarCollapsed }">
      <!-- AI Chat View -->
      <AIChat
        v-if="activeTab === 'ai'"
        :materialData="materialData || null"
        :structureData="structureData || null"
        class="ai-chat-view"
      />
      
      <!-- Save/Load View -->
      <SaveLoad
        v-else-if="activeTab === 'save'"
        :materialData="materialData || null"
        :structureData="structureData || null"
        :papers="papers || []"
        :prices="prices || []"
        @loadData="handleLoadData"
        class="save-load-view"
      />
      
      <!-- Account Info View -->
      <AccountInfo
        v-else-if="activeTab === 'account'"
        class="account-info-view"
      />

      <!-- Settings View -->
      <Settings
        v-else-if="activeTab === 'settings'"
        class="settings-view"
      />
      
      <!-- Main Content View -->
      <div v-else class="container">
        <header>
          <h1>Molecule Scope</h1>
          <p>Interactive 3D visualization of Materials Project crystal structures with research and market data</p>
        </header>

      <div class="search-section">
        <div class="input-group">
          <input
            v-model="searchQuery"
            placeholder="Enter Materials Project ID, formula, or name (e.g., mp-149, Si, silicon, 硅)"
            @keyup.enter="handleSearch"
          />
          <button @click="handleSearch" :disabled="loading">
            {{ loading ? 'Loading...' : 'Search' }}
          </button>
        </div>
        
        <!-- Search results dropdown -->
        <div v-if="searchResults.length > 0" class="search-results">
          <div class="search-result-item"
               v-for="result in searchResults"
               :key="result.material_id"
               @click="selectMaterial(result)">
            <strong>{{ result.formula_pretty }}</strong> - {{ result.material_id }}
            <div class="result-details">
              <span v-if="result.symmetry">Space group: {{ result.symmetry.symbol }}</span>
              <span v-if="result.band_gap !== undefined">Band gap: {{ result.band_gap.toFixed(2) }} eV</span>
            </div>
          </div>
        </div>
      </div>

      <div v-if="error" class="error">
        {{ error }}
      </div>

      <div v-if="loading" class="loading">
        <p>Loading material data and research information...</p>
      </div>

      <div v-else-if="materialData && materialData.material_id" class="content">
        <!-- Top Section: Material Info and 3D Visualization -->
        <div class="top-section">
          <div class="material-info">
            <h2>{{ materialData?.formula_pretty || 'N/A' }}</h2>
            

            <!-- Electronic Properties -->
            <div class="info-section">
              <div class="section-header">
                <h3>⚡ Electronic Properties</h3>
                <button class="toggle-btn" @click="toggleSection('electronic')">
                  {{ sectionStates.electronic ? '−' : '+' }}
                </button>
              </div>
              <div v-if="sectionStates.electronic" class="section-content">
                <p><strong>Band Gap:</strong> {{ materialData?.band_gap?.toFixed(2) || 'N/A' }} eV</p>
                <p><strong>Direct Band Gap:</strong> {{ materialData?.is_gap_direct !== undefined ? (materialData.is_gap_direct ? 'Yes' : 'No') : 'N/A' }}</p>
                <p><strong>Metal:</strong> {{ materialData?.is_metal !== undefined ? (materialData.is_metal ? 'Yes' : 'No') : 'N/A' }}</p>
                <p><strong>Fermi Energy:</strong> {{ materialData?.efermi?.toFixed(2) || 'N/A' }} eV</p>
              </div>
            </div>

            <!-- Magnetic Properties -->
            <div class="info-section">
              <div class="section-header">
                <h3>🧲 Magnetic Properties</h3>
                <button class="toggle-btn" @click="toggleSection('magnetic')">
                  {{ sectionStates.magnetic ? '−' : '+' }}
                </button>
              </div>
              <div v-if="sectionStates.magnetic" class="section-content">
                <p><strong>Magnetic:</strong> {{ materialData?.is_magnetic !== undefined ? (materialData.is_magnetic ? 'Yes' : 'No') : 'N/A' }}</p>
                <p><strong>Total Magnetization:</strong> {{ materialData?.total_magnetization?.toFixed(2) || 'N/A' }} μB</p>
              </div>
            </div>

            <!-- Energy Properties -->
            <div class="info-section">
              <div class="section-header">
                <h3>🔋 Energy Properties</h3>
                <button class="toggle-btn" @click="toggleSection('energy')">
                  {{ sectionStates.energy ? '−' : '+' }}
                </button>
              </div>
              <div v-if="sectionStates.energy" class="section-content">
                <p><strong>Energy per Atom:</strong> {{ materialData?.energy_per_atom?.toFixed(2) || 'N/A' }} eV/atom</p>
                <p><strong>Formation Energy:</strong> {{ materialData?.formation_energy_per_atom?.toFixed(2) || 'N/A' }} eV/atom</p>
                <p><strong>Energy Above Hull:</strong> {{ materialData?.energy_above_hull?.toFixed(2) || 'N/A' }} eV/atom</p>
                <p><strong>Decomposition Energy:</strong> {{ materialData?.decomposition_energy?.toFixed(2) || 'N/A' }} eV/atom</p>
              </div>
            </div>

            <!-- Mechanical Properties -->
            <div class="info-section">
              <div class="section-header">
                <h3>⚙️ Mechanical Properties</h3>
                <button class="toggle-btn" @click="toggleSection('mechanical')">
                  {{ sectionStates.mechanical ? '−' : '+' }}
                </button>
              </div>
              <div v-if="sectionStates.mechanical" class="section-content">
                <p><strong>Bulk Modulus:</strong> {{ materialData?.bulk_modulus?.vrh?.toFixed(2) || 'N/A' }} GPa</p>
                <p><strong>Shear Modulus:</strong> {{ materialData?.shear_modulus?.vrh?.toFixed(2) || 'N/A' }} GPa</p>
                <p><strong>Poisson's Ratio:</strong> {{ materialData?.poisson_ratio?.toFixed(2) || 'N/A' }}</p>
              </div>
            </div>

            <!-- Surface Properties -->
            <div class="info-section">
              <div class="section-header">
                <h3>🌐 Surface Properties</h3>
                <button class="toggle-btn" @click="toggleSection('surface')">
                  {{ sectionStates.surface ? '−' : '+' }}
                </button>
              </div>
              <div v-if="sectionStates.surface" class="section-content">
                <p><strong>Surface Energy:</strong> {{ materialData?.surface_energy !== null ? materialData.surface_energy.toFixed(2) : 'N/A' }} J/m²</p>
                <p><strong>Work Function:</strong> {{ materialData?.work_function !== null ? materialData.work_function.toFixed(2) : 'N/A' }} eV</p>
              </div>
            </div>
                      <!-- Crystal Structure Information -->
          <div class="info-section">
            <div class="section-header">
              <h3>🔬 Crystal Structure</h3>
              <button class="toggle-btn" @click="toggleSection('crystal')">
                {{ sectionStates.crystal ? '−' : '+' }}
              </button>
            </div>
            <div v-if="sectionStates.crystal" class="section-content">
              <p><strong>Material ID:</strong> {{ materialData?.material_id || 'N/A' }}</p>
              <p><strong>Crystal System:</strong> {{ materialData?.symmetry?.crystal_system || 'N/A' }}</p>
              <p><strong>Space Group:</strong> {{ materialData?.symmetry?.symbol || 'N/A' }}</p>
              <p><strong>Space Group Number:</strong> {{ materialData?.symmetry?.number || 'N/A' }}</p>
              <p><strong>Volume:</strong> {{ materialData?.volume?.toFixed(2) || 'N/A' }} Å³</p>
              <p><strong>Density:</strong> {{ materialData?.density?.toFixed(2) || 'N/A' }} g/cm³</p>
              <p><strong>Number of Sites:</strong> {{ materialData?.nsites || 'N/A' }}</p>
              <p><strong>Number of Elements:</strong> {{ materialData?.nelements || 'N/A' }}</p>
              <p><strong>Elements:</strong> {{ materialData?.elements?.join(', ') || 'N/A' }}</p>
              
              <!-- Lattice Parameters -->
              <div v-if="structureData && structureData.lattice" class="lattice-parameters">
                <h4>Lattice Parameters:</h4>
                <p><strong>a:</strong> {{ structureData.lattice.a?.toFixed(3) || 'N/A' }} Å</p>
                <p><strong>b:</strong> {{ structureData.lattice.b?.toFixed(3) || 'N/A' }} Å</p>
                <p><strong>c:</strong> {{ structureData.lattice.c?.toFixed(3) || 'N/A' }} Å</p>
                <p><strong>α:</strong> {{ structureData.lattice.alpha?.toFixed(1) || 'N/A' }}°</p>
                <p><strong>β:</strong> {{ structureData.lattice.beta?.toFixed(1) || 'N/A' }}°</p>
                <p><strong>γ:</strong> {{ structureData.lattice.gamma?.toFixed(1) || 'N/A' }}°</p>
              </div>
              
              <!-- Unit Cell Information -->
              <div v-if="structureData && structureData.lattice" class="unit-cell-info">
                <h4>Unit Cell:</h4>
                <p><strong>Formula Units:</strong> {{ materialData?.formula_units_per_cell || 'N/A' }}</p>
                <p><strong>Atoms per Cell:</strong> {{ materialData?.nsites || 'N/A' }}</p>
                <p><strong>Cell Volume:</strong> {{ materialData?.volume?.toFixed(2) || 'N/A' }} Å³</p>
              </div>
            </div>
          </div>
          </div>



          <div class="visualization">
            <h3>3D Structure Visualization</h3>
            <div v-if="structureLoading" class="loading-small">
              <p>Loading 3D structure...</p>
            </div>
            <div v-else-if="structureError" class="error-small">
              {{ structureError }}
            </div>
            <div v-else-if="!structureData" class="no-data">
              <p>No structure data available</p>
            </div>
            <MoleculeViewer
              v-else-if="structureData && structureData.sites"
              :structureData="structureData"
              :materialId="materialData?.material_id || ''"
              :materialData="materialData"
              :displayMode="moleculeDisplayMode"
              :crystalMode="crystalMode"
              :unitCells="unitCells"
              :key="'molecule-' + (structureData?.material_id || materialData?.material_id || 'unknown') + '-' + moleculeDisplayMode + '-' + crystalMode + '-' + unitCells"
            />
          </div>
        </div>

        <!-- Bottom Section: Papers and Price Information -->
        <div class="bottom-section">
          <div class="papers-section">
            <h3>📚 Latest Research Papers</h3>
            <div v-if="papersLoading" class="loading-small">
              <p>Loading research papers...</p>
            </div>
            <div v-else-if="papersError" class="error-small">
              {{ papersError }}
            </div>
            <div v-else-if="papers.length === 0" class="no-data">
              <p>No research papers found</p>
            </div>
            <div v-else class="papers-list">
              <div v-for="(paper, index) in papers" :key="index" class="paper-item">
                <h4>{{ paper.title }}</h4>
                <p class="paper-abstract">{{ paper.abstract }}</p>
                <div class="paper-meta">
                  <span class="source">{{ paper.source }}</span>
                  <span class="timestamp">{{ formatDate(paper.timestamp) }}</span>
                </div>
                <a :href="paper.url" target="_blank" class="paper-link">Read paper →</a>
              </div>
            </div>
          </div>

          <div class="prices-section">
            <h3>💰 Market Prices & Suppliers</h3>
            <div v-if="pricesLoading" class="loading-small">
              <p>Loading price information...</p>
            </div>
            <div v-else-if="pricesError" class="error-small">
              {{ pricesError }}
            </div>
            <div v-else-if="prices.length === 0" class="no-data">
              <p>No price information found</p>
            </div>
            <div v-else class="prices-list">
              <div v-for="(price, index) in prices" :key="index" class="price-item">
                <h4>{{ price.title }}</h4>
                <div class="price-details">
                  <span v-if="price.price" class="price-amount">
                    {{ price.currency }} {{ price.price }}
                  </span>
                  <span v-if="price.supplier" class="supplier">
                    Supplier: {{ price.supplier }}
                  </span>
                  <span v-if="price.quantity" class="quantity">
                    Quantity: {{ price.quantity }}
                  </span>
                </div>
                <p class="price-abstract">{{ price.abstract }}</p>
                <div class="price-meta">
                  <span class="source">{{ price.source }}</span>
                  <span class="timestamp">{{ formatDate(price.timestamp) }}</span>
                </div>
                <a :href="price.url" target="_blank" class="price-link">View offer →</a>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div v-else class="welcome">
        <h2>Welcome to Molecule Scope</h2>
        <p>Enter a Materials Project ID to visualize crystal structures and get research/market data.</p>
        <p>Example IDs: mp-149 (Silicon), mp-66 (Diamond), mp-1840 (Quartz)</p>
        <div class="api-note">
          <p>📝 Note: Make sure the FastAPI backend server is running on localhost:8001</p>
          <p>The backend will handle API communication with Materials Project and Baidu search</p>
        </div>
      </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import MoleculeViewer from './components/MoleculeViewer.vue'
import AIChat from './components/AIChat.vue'
import SaveLoad from './components/SaveLoad.vue'
import AccountInfo from './components/AccountInfo.vue'
import Settings from './components/Settings.vue'
import apiService from './services/newApiService'

export default {
  name: 'App',
  components: {
    MoleculeViewer,
    AIChat,
    SaveLoad,
    AccountInfo,
    Settings
  },
  setup() {
    // Ensure all refs are properly initialized
    const searchQuery = ref('')
    const materialId = ref('')
    const materialData = ref(null)
    const structureData = ref(null)
    const papers = ref([])
    const prices = ref([])
    const searchResults = ref([])
    const loading = ref(false)
    const structureLoading = ref(false)
    const papersLoading = ref(false)
    const pricesLoading = ref(false)
    const error = ref('')
    const structureError = ref('')
    const papersError = ref('')
    const pricesError = ref('')
    const isSidebarCollapsed = ref(false)
    const activeTab = ref('query')
    const moleculeDisplayMode = ref('ball') // 默认显示模式
    const crystalMode = ref(false) // 默认晶体模式
    const unitCells = ref(1) // 默认晶胞数量

    const toggleSidebar = () => {
      isSidebarCollapsed.value = !isSidebarCollapsed.value
    }

    const setActiveTab = (tab) => {
      activeTab.value = tab
      // 这里可以添加不同标签页的逻辑
      console.log('Active tab:', tab)
    }

    // Collapsible section states
    const sectionStates = ref({
      crystal: true,
      electronic: true,
      magnetic: true,
      energy: true,
      mechanical: true,
      surface: true
    })

    const toggleSection = (section) => {
      sectionStates.value[section] = !sectionStates.value[section]
    }

    const handleSearch = async () => {
      if (!searchQuery.value.trim()) {
        error.value = 'Please enter a search query'
        return
      }

      // 如果输入的是mp开头的ID，直接获取材料详情
      if (searchQuery.value.trim().toLowerCase().startsWith('mp-')) {
        materialId.value = searchQuery.value.trim()
        searchResults.value = []
        fetchMaterialData()
        return
      }

      loading.value = true
      searchResults.value = []
      error.value = ''
      
      try {
        // First try to search for materials
        const searchResult = await apiService.searchMaterials(searchQuery.value.trim(), 10)
        if (searchResult.count > 0) {
          searchResults.value = searchResult.results
        } else {
          error.value = 'No materials found. Please try a different search term.'
        }
      } catch (err) {
        error.value = 'Search failed: ' + (err.response?.data?.detail || err.message)
        console.error('Search error:', err)
      } finally {
        loading.value = false
      }
    }

    const selectMaterial = (material) => {
      materialId.value = material.material_id
      searchResults.value = []
      fetchMaterialData()
    }

    const fetchMaterialData = async () => {
      if (!materialId.value.trim()) {
        error.value = 'Please enter a Materials Project ID'
        return
      }

      loading.value = true
      error.value = ''
      structureError.value = ''
      papersError.value = ''
      pricesError.value = ''
      
      try {
        // Fetch material details
        const data = await apiService.getMaterialDetails(materialId.value.trim())
        materialData.value = data

        // Fetch structure, papers and prices in parallel
        structureLoading.value = true
        papersLoading.value = true
        pricesLoading.value = true
        
        try {
          const structure = await apiService.getCrystalStructure(materialId.value.trim())
          console.log('Structure data received:', structure)
          
          // Verify structure data format
          if (structure && structure.sites && structure.lattice) {
            console.log(`Structure contains ${structure.sites.length} atoms`);
            console.log('Lattice parameters:', structure.lattice);
            console.log('Setting structureData.value...');
            // Use Vue's nextTick to ensure reactivity works properly
            structureData.value = JSON.parse(JSON.stringify(structure)); // Deep clone to ensure reactivity
            console.log('structureData.value set:', structureData.value);
            console.log('Structure data has sites:', structureData.value.sites?.length);
            console.log('Structure data material_id:', structureData.value.material_id);
            
            // Force update to ensure reactivity
            structureData.value = {...structureData.value};
            
            // Debug: Check if structureData has the expected properties for MoleculeViewer
            console.log('structureData properties for MoleculeViewer:', Object.keys(structureData.value));
            if (structureData.value.sites) {
              console.log('First site:', structureData.value.sites[0]);
            }
          } else {
            console.error('Invalid structure data format:', structure);
            structureError.value = 'Invalid structure data format received'
          }
        } catch (err) {
          structureError.value = 'Failed to fetch crystal structure: ' + (err.message || 'API connection timeout')
          console.error('Error fetching structure:', err)
          
          // Provide mock structure data for demo purposes
          console.log('Providing mock structure data for demo');
          structureData.value = {
            material_id: materialId.value,
            lattice: {
              a: 5.43, b: 5.43, c: 5.43,
              alpha: 90, beta: 90, gamma: 90,
              volume: 160.0
            },
            sites: [
              {species: ['Si'], xyz: [0, 0, 0], label: 'Si'},
              {species: ['Si'], xyz: [0.5, 0.5, 0], label: 'Si'},
              {species: ['Si'], xyz: [0.5, 0, 0.5], label: 'Si'},
              {species: ['Si'], xyz: [0, 0.5, 0.5], label: 'Si'},
              {species: ['Si'], xyz: [0.25, 0.25, 0.25], label: 'Si'},
              {species: ['Si'], xyz: [0.75, 0.75, 0.25], label: 'Si'},
              {species: ['Si'], xyz: [0.75, 0.25, 0.75], label: 'Si'},
              {species: ['Si'], xyz: [0.25, 0.75, 0.75], label: 'Si'}
            ]
          };
        } finally {
          structureLoading.value = false
        }

        try {
          const papersData = await apiService.getMaterialPapers(materialId.value.trim())
          papers.value = papersData
        } catch (err) {
          papersError.value = 'Failed to fetch research papers'
          console.error('Error fetching papers:', err)
        } finally {
          papersLoading.value = false
        }

        try {
          const pricesData = await apiService.getMaterialPrices(materialId.value.trim())
          prices.value = pricesData
        } catch (err) {
          pricesError.value = 'Failed to fetch price information'
          console.error('Error fetching prices:', err)
        } finally {
          pricesLoading.value = false
        }

      } catch (err) {
        error.value = err.message || 'Failed to fetch material data'
        materialData.value = null
        structureData.value = null
        papers.value = []
        prices.value = []
      } finally {
        loading.value = false
      }
    }

    const formatDate = (timestamp) => {
      if (!timestamp) return 'Unknown date'
      try {
        const date = new Date(timestamp)
        return date.toLocaleDateString('zh-CN', {
          year: 'numeric',
          month: 'short',
          day: 'numeric'
        })
      } catch {
        return timestamp
      }
    }

    const handleLoadData = (loadedData) => {
      materialData.value = loadedData.materialData
      structureData.value = loadedData.structureData || null
      papers.value = loadedData.papers || []
      prices.value = loadedData.prices || []
      
      // 切换到查询视图显示加载的数据
      activeTab.value = 'query'
    }

    // 加载设置
    const loadSettings = () => {
      try {
        const savedSettings = localStorage.getItem('appSettings')
        if (savedSettings) {
          const settings = JSON.parse(savedSettings)
          moleculeDisplayMode.value = settings.moleculeDisplayMode || 'ball'
          crystalMode.value = settings.crystalMode || false
          unitCells.value = settings.unitCells || 1
        }
      } catch (error) {
        console.error('加载设置失败:', error)
      }
    }

    // 监听设置变化
    const setupSettingsListener = () => {
      // 监听自定义事件（同一标签页内设置更改）
      window.addEventListener('appSettingsChanged', (event) => {
        try {
          moleculeDisplayMode.value = event.detail.settings.moleculeDisplayMode || 'ball'
          crystalMode.value = event.detail.settings.crystalMode || false
          unitCells.value = event.detail.settings.unitCells || 1
        } catch (error) {
          console.error('解析设置失败:', error)
        }
      })
      
      // 监听storage事件（跨标签页设置更改）
      window.addEventListener('storage', (event) => {
        if (event.key === 'appSettings' && event.newValue) {
          try {
            const settings = JSON.parse(event.newValue)
            moleculeDisplayMode.value = settings.moleculeDisplayMode || 'ball'
            crystalMode.value = settings.crystalMode || false
            unitCells.value = settings.unitCells || 1
          } catch (error) {
            console.error('解析设置失败:', error)
          }
        }
      })
    }

    // 初始化加载设置
    onMounted(() => {
      loadSettings()
      setupSettingsListener()
    })

    return {
      searchQuery,
      searchResults,
      materialId,
      materialData,
      papers,
      prices,
      loading,
      structureLoading,
      papersLoading,
      pricesLoading,
      error,
      structureError,
      papersError,
      pricesError,
      isSidebarCollapsed,
      activeTab,
      moleculeDisplayMode,
      crystalMode,
      unitCells,
      handleSearch,
      selectMaterial,
      fetchMaterialData,
      formatDate,
      toggleSidebar,
      setActiveTab,
      handleLoadData,
      structureData,
      sectionStates,
      toggleSection
    }
  }
}
</script>

<style>
@import './assets/theme.css';

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
}

#app {
  min-height: 100vh;
  display: flex;
}

/* 侧边栏样式 */
.sidebar {
  width: 250px;
  background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
  color: white;
  transition: width 0.3s ease;
  display: flex;
  flex-direction: column;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
}

.sidebar-collapsed {
  width: 60px;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  display: flex;
  align-items: center;
  gap: 10px;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.toggle-sidebar {
  background: rgba(255, 255, 255, 0.1);
  border: none;
  color: white;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  transition: background 0.3s ease;
}

.toggle-sidebar:hover {
  background: rgba(255, 255, 255, 0.2);
}

.sidebar-content {
  padding: 20px 0;
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.sidebar-btn {
  background: transparent;
  border: none;
  color: white;
  padding: 15px 20px;
  margin: 0 10px;
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 12px;
  transition: all 0.3s ease;
  text-align: left;
  font-size: 14px;
}

.sidebar-btn:hover {
  background: rgba(255, 255, 255, 0.1);
}

.sidebar-btn.active {
  background: rgba(52, 152, 219, 0.2);
  border-left: 3px solid #3498db;
}

.btn-icon {
  font-size: 18px;
  min-width: 24px;
  text-align: center;
}

.account-btn {
  margin-top: auto;
  margin-bottom: 20px;
}

/* 主内容区域样式 */
.main-content {
  flex: 1;
  transition: margin-left 0.3s ease;
  min-height: 100vh;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.main-content.sidebar-expanded {
  margin-left: 0;
}

/* AI聊天视图样式 */
.ai-chat-view {
  height: 100vh;
  background: #f8f9fa;
  display: flex;
  flex-direction: column;
}

/* 保存/加载视图样式 */
.save-load-view {
  height: 100vh;
  background: #f8f9fa;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

/* 账户信息视图样式 */
.account-info-view {
  height: 100vh;
  background: #f8f9fa;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

/* 设置视图样式 */
.settings-view {
  height: 100vh;
  background: #f8f9fa;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.container {
  flex: 1;
  display: flex;
  flex-direction: column;
  max-width: none;
  margin: 0;
  background: white;
  border-radius: 0;
  box-shadow: none;
  overflow: hidden;
}

header {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  padding: 30px;
  text-align: center;
}

header h1 {
  font-size: 2.5rem;
  margin-bottom: 10px;
}

header p {
  font-size: 1.1rem;
  opacity: 0.9;
}

.search-section {
  padding: 30px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.input-group {
  display: flex;
  gap: 10px;
  max-width: 500px;
  margin: 0 auto;
}

.input-group input {
  flex: 1;
  padding: 12px 16px;
  border: 2px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
  outline: none;
  transition: border-color 0.3s ease;
}

.input-group input:focus {
  border-color: #4facfe;
}

.input-group button {
  padding: 12px 24px;
  background: #4facfe;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: background 0.3s ease;
}

.input-group button:hover:not(:disabled) {
  background: #3a8fd4;
}

.input-group button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.error {
  background: #fee;
  color: #c33;
  padding: 15px;
  margin: 20px;
  border-radius: 8px;
  border: 1px solid #fcc;
}

.error-small {
  background: #fee;
  color: #c33;
  padding: 10px;
  margin: 10px 0;
  border-radius: 6px;
  border: 1px solid #fcc;
  font-size: 14px;
}

.loading {
  text-align: center;
  padding: 40px;
  color: #666;
}

.loading-small {
  text-align: center;
  padding: 20px;
  color: #666;
  font-size: 14px;
}

.no-data {
  text-align: center;
  padding: 20px;
  color: #999;
  font-style: italic;
}

.content {
  padding: 30px;
}

.top-section {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 30px;
  margin-bottom: 30px;
}

.bottom-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 30px;
}

.material-info {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  max-height: 600px;
  overflow-y: auto;
}

.material-info h2 {
  color: #333;
  margin-bottom: 20px;
  text-align: center;
  font-size: 1.8rem;
}

.info-section {
  margin-bottom: 20px;
  padding: 15px;
  background: white;
  border-radius: 8px;
  border-left: 4px solid #4facfe;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.info-section h3 {
  color: #2c3e50;
  margin-bottom: 12px;
  font-size: 1.1rem;
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-section p {
  margin: 6px 0;
  color: #555;
  font-size: 14px;
  line-height: 1.4;
}

.info-section p strong {
  color: #2c3e50;
  min-width: 140px;
  display: inline-block;
}

/* 晶胞信息子标题样式 */
.lattice-parameters h4,
.unit-cell-info h4 {
  color: #3498db;
  margin: 15px 0 10px 0;
  font-size: 14px;
  border-bottom: 1px solid #eee;
  padding-bottom: 5px;
}

.lattice-parameters p,
.unit-cell-info p {
  margin: 5px 0;
  font-size: 13px;
}

.lattice-parameters p strong,
.unit-cell-info p strong {
  min-width: 120px;
  color: #7f8c8d;
}

/* 晶胞参数特殊样式 */
.lattice-parameters {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 6px;
  margin: 10px 0;
  border-left: 3px solid #3498db;
}

.unit-cell-info {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 6px;
  margin: 10px 0;
  border-left: 3px solid #e74c3c;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.section-header h3 {
  color: #2c3e50;
  font-size: 1.1rem;
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
}

.toggle-btn {
  background: #4facfe;
  color: white;
  border: none;
  width: 24px;
  height: 24px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: bold;
  transition: background 0.3s ease;
}

.toggle-btn:hover {
  background: #3a8fd4;
}

.section-content {
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-5px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.visualization {
  background: #fff;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 20px;
}

.visualization h3 {
  margin-bottom: 15px;
  color: #333;
}

.papers-section, .prices-section {
  background: #fff;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 20px;
  max-height: 600px;
  overflow-y: auto;
}

.papers-section h3, .prices-section h3 {
  margin-bottom: 15px;
  color: #333;
  display: flex;
  align-items: center;
  gap: 8px;
}

.paper-item, .price-item {
  border-bottom: 1px solid #eee;
  padding: 15px 0;
  margin-bottom: 15px;
}

.paper-item:last-child, .price-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.paper-item h4, .price-item h4 {
  color: #2c3e50;
  margin-bottom: 8px;
  font-size: 16px;
  line-height: 1.4;
}

.paper-abstract, .price-abstract {
  color: #666;
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 10px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.paper-meta, .price-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  font-size: 12px;
  color: #888;
}

.source {
  background: #e3f2fd;
  padding: 2px 8px;
  border-radius: 4px;
  font-weight: 500;
}

.timestamp {
  color: #666;
}

.price-details {
  display: flex;
  gap: 15px;
  margin-bottom: 8px;
  font-size: 14px;
}

.price-amount {
  color: #e74c3c;
  font-weight: bold;
}

.supplier, .quantity {
  color: #7f8c8d;
}

.paper-link, .price-link {
  color: #3498db;
  text-decoration: none;
  font-size: 14px;
  font-weight: 500;
}

.paper-link:hover, .price-link:hover {
  text-decoration: underline;
}

.welcome {
  text-align: center;
  padding: 60px 30px;
  color: #666;
}

.welcome h2 {
  margin-bottom: 20px;
  color: #333;
}

.welcome p {
  margin: 10px 0;
  font-size: 16px;
}

.api-note {
  margin-top: 30px;
  padding: 15px;
  background: #e7f3ff;
  border-radius: 8px;
  border-left: 4px solid #4facfe;
}

.api-note p {
  margin: 5px 0;
  font-size: 14px;
  color: #555;
}

@media (max-width: 1024px) {
  .top-section {
    grid-template-columns: 1fr;
  }
  
  .bottom-section {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .content {
    padding: 20px;
  }
  
  .input-group {
    flex-direction: column;
  }
  
  header h1 {
    font-size: 2rem;
  }
  
  .price-details {
    flex-direction: column;
    gap: 5px;
  }
  
  .container {
    border-radius: 0;
  }
}
</style>
